<?php

namespace app\api\controller;


use app\admin\model\BillModel;
use app\admin\model\BuildingModel;
use app\admin\model\BuildingRoomBoardModel;
use app\admin\model\BuildingRoomModel;
use app\admin\model\ContractFixedModel;
use app\admin\model\RoomBoardLogModel;
use app\common\controller\Api;
use app\common\model\PaymentRecords;
use think\Db;
use think\Exception;
use think\exception\PDOException;


class Biao extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * @var BuildingRoomModel
     */
    protected $model = null;

    protected $user_id = 0;

    protected $board_list = [
        1 => '水表',
        2 => '电表',
        3 => '燃气',
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new BuildingRoomModel();
        $this->user_id = $this->auth->id;
    }

    public function index()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $type = $this->request->param('type/d', 0);
        $build_id = $this->request->param('build_id/d', 0);
        $flag = $this->request->param('flag/d', 0);
        $kw = $this->request->param('kw/s', '');
        $where = [];
        if ($kw) {
            $where['name'] = ['like', '%' . $kw . '%'];
        }


        $build_ids = BuildingModel::getUserBuildingIds($this->auth->id);
        if ($build_id) {
            $build_ids = $build_id;
        }
        $where['build_id'] = ['in', $build_ids];

        if ($flag == 1) {
            $where['status'] = 0;
        } elseif ($flag == 2) {
            $where['status'] = 3;
        } elseif ($flag == 3) {
            $where['is_remind'] = 1;
        }


        $list = $this->model->alias('r')
            ->join('building b', 'r.build_id = b.id', 'left')
            ->where($where)
            ->field('b.name as build_name,b.address,r.name,r.id as room_id')
            ->order('build_id asc,name asc')
            ->paginate($page_size)->each(function ($item) use ($type) {
                $item->append([], true);
                $item->borad = $this->getBoardInfo($item->room_id, $type);

            });

        $this->success('成功', $list);
    }

    private function getBoardInfo($room_id, $type)
    {

        $data = [];

        foreach ($this->board_list as $k => $name) {
            if ($type && $k != $type) {
                continue;
            }

            $board_log = RoomBoardLogModel::where([
                'room_id' => $room_id,
                'type' => $k
            ])
                ->order('id desc')
                ->field('num,last_num,create_time')
                ->find();
            $data[] = [
                'type' => $k,
                'name' => $name,
                'num' => $board_log['num'] ?? 0,
                'last_num' => $board_log['last_num'] ?? 0,
                'new_num' => '',
                'time' => date('m-d H:i', $board_log['create_time'] ?? time()),
            ];
        }

        return $data;
    }

    public function add()
    {
        $room_id = $this->request->param('room_id/d', 0);
        $type = $this->request->param('type/d', 0);
        $num = $this->request->param('new_num/d', 0);
        if ($room_id < 1) {
            $this->error('id错误');
        }

        if (!array_key_exists($type, $this->board_list)) {
            $this->error('type错误');
        }

        if ($num < 0) {
            $this->error('num错误');
        }

        $room = $this->model->where(['id' => $room_id])->find();
        if (!$room) {
            $this->error('房间不存在');
        }

        $last_board = RoomBoardLogModel::where([
            'room_id' => $room_id,
            'type' => $type
        ])
            ->order('id desc')
            ->find();


        $last_num = $last_board->num ?? 0;

        if ($num < $last_num) {
            $this->error('最新值不能小于上期');
        }

        Db::startTrans();
        try {
            $price = BuildingRoomBoardModel::where([
                'room_id' => $room_id,
                'type' => $type
            ])->value('price', 0);

            $use_num = $num - $last_num;
            $money = bcmul($use_num, $price, 2);
            $log = RoomBoardLogModel::create([
                'user_id' => $this->user_id,
                'room_id' => $room_id,
                'type' => $type,
                'name' => $this->board_list[$type],
                'num' => $num,
                'last_num' => $last_num,
                'use_num' => $use_num,
                'price' => $price,
                'money' => $money,
                'month' => date('Y-m', time()),
            ]);

            BuildingRoomBoardModel::update(['last_num' => $last_num], [
                'room_id' => $room_id,
                'type' => $type
            ]);

            $contract = \app\common\model\Contract::where('room_id', $room_id)
                ->order('id', 'desc')->find();

            if ($contract) {
                // 房东端账单
                $fee_arr = [
                    1 => '水费',
                    2 => '电费',
                    3 => '燃气费',
                ];
                $start_date = $contract->start_time;
                if ($last_board) {
                    $start_date = date('Y-m-d', $last_board->create_time);
                }
                $period = $start_date . '至' . date('Y-m-d');
                $category = $fee_arr[$type] ?? '未知';
                $bill = BillModel::create([
                    'user_id' => $contract->homeowner_id,
                    'contract_id' => $contract->id,
                    'status' => 0,
                    'money' => $money,
                    'year' => date('Y'),
                    'month' => date('Y-m'),
                    'day' => date('Y-m-d'),
                    'category' => $category,
                    'type' => $type + 2,//转换一下
                    'remark' => $category,
                    'period' => $period,
                    'rid' => $log->id ?? 0,
                ], true);


                // 用户端缴费
                $insert_data = [
                    'homeowner_id' => $contract->homeowner_id,
                    'contract_id' => $contract->id,
                    'relation_id' => $bill->id,
                    'user_id' => $contract->user_id,
                    'type' => PaymentRecords::TYPE_OTHER,
                    //'water_photo' => '',
                    //'electricity_photo' => '',
                    'status' => PaymentRecords::STATUS_DEFAULT,
                    'money' => $money,
                ];

                if ($type == 1) {
                    $insert_data['water_num'] = $num;
                    $insert_data['last_water_num'] = $last_num;
                    $insert_data['money_water'] = $money;
                } elseif ($type == 2) {
                    $insert_data['electricity_num'] = $num;
                    $insert_data['last_electricity_num'] = $last_num;
                    $insert_data['money_electricity'] = $money;
                } else {
                    $insert_data['other_fee'] = $money;
                    $other_data = [
                        [
                            'name' => '燃气费',
                            'money' => $money,
                        ]
                    ];
                    $insert_data['other_data'] = json_encode($other_data, JSON_UNESCAPED_UNICODE);
                }


                PaymentRecords::create($insert_data, true);
            }


            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('ok');
    }


    public function log()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $room_id = $this->request->param('room_id/d', 0);
        $type = $this->request->param('type/d', 0);


        $where['room_id'] = $room_id;
        $where['type'] = $type;
        $list = RoomBoardLogModel::where($where)
            ->with('user')
            ->field('user_id,room_id,type,name,num,create_time')
            ->order('id desc')
            ->paginate($page_size)->each(function ($item) {
                $item->time_text = date('Y-m-d H:i', $item->create_time);
            });

        $this->success('成功', $list);
    }

}
